package com.ldc.commonres.common

import android.app.Activity
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.android.arouter.launcher.ARouter
import com.ldc.commonlibs.conf.AppConf
import com.ldc.commonlibs.listener.OnRowListener
import com.ldc.commonres.views.StateViewLayout
import me.jessyan.autosize.internal.CustomAdapt

abstract class ActivityBase : AppCompatActivity(), CustomAdapt {

    protected val TAG: String = "【%s】".format(this::class.java.name)
    open var activity: Activity? = null
    private var stateViewLayout: StateViewLayout? = null

    // 消息处理器
    private val callback = Handler.Callback { p0 -> processMessage(p0) }
    private val handler: Handler = Handler(Looper.getMainLooper(), callback)

    // 消息分发
    open fun processMessage(msg: Message): Boolean {
        return false
    }

    // 获取消息处理器
    fun getHandler(): Handler = handler

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        try {
            activity = this
            ARouter.getInstance().inject(this)
            // 禁用横屏
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
            setContentView(loadView())
            stateViewLayout = initStateViewLayout()
            start(savedInstanceState)
            main()
        } catch (e: Exception) {
            processError(e)
        }
    }

    open fun loadView(): View? = null
    open fun start(savedInstanceState: Bundle?) {}
    abstract fun main()
    open fun processError(e: Exception) {
        e.printStackTrace()
    }

    open fun initStateViewLayout(): StateViewLayout? = null
    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacksAndMessages(null)
    }

    override fun isBaseOnWidth(): Boolean = AppConf.isBaseOnWidth
    override fun getSizeInDp(): Float = AppConf.getSizeInDp

    protected fun showContentView() {
        stateViewLayout?.showContentView()
    }

    protected fun showLoadingView() {
        stateViewLayout?.showLoadingView()
    }

    protected fun showErrorView() {
        stateViewLayout?.showErrorView()
    }

    protected fun showSuccessView() {
        stateViewLayout?.showSuccessView()
    }

    protected fun showEmptyView() {
        stateViewLayout?.showEmptyView()
    }
    protected fun addOnReTryListener(l: OnRowListener<Int>) {
        stateViewLayout?.addOnRetryListener(l)
    }

}